<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader class="product_tabs" hidden-breadcrumb>
                <div slot="title">
                <router-link :to="{ path: '/admin/marketing/feedback/disposition' }"
                    ><Button icon="ios-arrow-back" size="small" class="mr20"
                    >返回</Button
                    ></router-link
                >
                <span
                    v-text="$route.params.id ? '编辑问卷' : '添加问卷'"
                    class="mr20"
                ></span>
                </div>
            </PageHeader>
        </div>
        <div class="survey-header">
            <Input v-model="surveyTitle" placeholder="请输入问卷标题" style="width:300px;margin-right:20px"/>
            <i-switch
              v-model="surveyStatus"
              :value="surveyStatus"
              :true-value="1"
              :false-value="0"
              size="large"
            >
              <span slot="open">上架</span>
              <span slot="close">下架</span>
            </i-switch>
        </div>
        <div class="survey-header">
            <Input v-model="top_desc" placeholder="请输入顶部描述" style="width:300px;margin-right:20px"/>
            <Input v-model="bottom_desc" placeholder="请输入底部描述" style="width:300px;margin-right:20px"/>
            <div class="custom-label" slot="label">
                <div class="leftnam">
                    <div>
                        <div>活动背景</div>
                    </div>
                    <div>：</div>
                </div>
                <div class="acea-row">
                    <div class="pictrue" v-if="bg_image">
                        <img class="image" v-lazy="bg_image" />
                        <Button
                        shape="circle"
                        icon="md-close"
                        @click.native="handleRemove()"
                        class="btndel"
                        ></Button>
                    </div>
                    <div
                        v-else
                        class="upLoad acea-row row-center-wrapper"
                        @click="modalPicTap('dan', 'danFrom')"
                    >
                        <Icon
                        type="ios-camera-outline"
                        size="26"
                        class="iconfonts"
                        />
                    </div>
                </div>
            </div>
        </div>
        <!-- 添加问题表单 -->
        <div class="question-form">
            <Select v-model="newQuestion.question_type" placeholder="选择题目类型" style="width:200px">
                <Option value="radio">单选</Option>
                <Option value="checkbox">多选</Option>
                <Option value="text">文本</Option>
                <Option value="rating">评分</Option> <!-- 新增评分类型 -->
            </Select>
            <Input v-model="newQuestion.question_text" placeholder="输入题目标题" style="width:300px;margin-left:10px;margin-right:20px"/>
            <i-switch
              v-model="newQuestion.is_required"
              :value="newQuestion.is_required"
              :true-value="1"
              :false-value="0"
              size="large"
            >
              <span slot="open">必填</span>
              <span slot="close">选填</span>
            </i-switch>
            <!-- 选项输入区域 -->
            <div v-if="newQuestion.question_type === 'radio' || newQuestion.question_type === 'checkbox'" class="options-area">
                <Input v-for="(option, index) in newQuestion.question_options" 
                       v-model="newQuestion.question_options[index]"
                       :key="index"
                       :placeholder="`选项 ${index + 1}`"
                       style="width:200px;margin:5px"/>
                <Button type="dashed" @click="addOption" style="margin:5px">添加选项</Button>
            </div>
            <!-- 评分范围设置 -->
            <div v-if="newQuestion.question_type === 'rating'" class="options-area">
                <InputNumber v-model="newQuestion.min" placeholder="最低分" style="width:100px;margin-right:10px"/>
                <InputNumber v-model="newQuestion.max" placeholder="最高分" style="width:100px"/>
            </div>
            <Button type="primary" @click="addQuestion" style="margin-left:10px" v-text="newQuestion.question_type ? '完成' : '添加问题'"></Button>
        </div>

        <!-- 问题列表 -->
        <draggable v-model="questions" handle=".handle">
            <div v-for="(question, index) in questions" :key="index" class="question-item">
                <Icon type="ios-menu" class="handle" style="cursor:move;margin-right:10px"/>
                <template v-if="!question.editing">
                    <span>{{ question.question_text }} ({{ question.question_type }})</span>
                    <!-- <Button type="primary" size="small" @click="editQuestion(index)" style="margin-left:10px">编辑</Button> -->
                    <Button type="error" size="small" @click="removeQuestion(index)" style="margin-left:10px">删除</Button>
                </template>
                <template v-else>
                    <Input v-model="question.question_text" style="width:200px;margin-right:10px"/>
                    <Select v-model="question.question_type" style="width:120px;margin-right:10px">
                        <Option value="radio">单选</Option>
                        <Option value="checkbox">多选</Option>
                        <Option value="text">文本</Option>
                        <Option value="rating">评分</Option>
                    </Select>
                    <div v-if="question.question_type === 'radio' || question.question_type === 'checkbox'" class="options-area">
                        <Input v-for="(option, optIndex) in question.question_options" 
                               v-model="question.question_options[optIndex]"
                               :key="optIndex"
                               :placeholder="`选项 ${optIndex + 1}`"
                               style="width:200px;margin:5px"/>
                        <Button type="dashed" @click="question.question_options.push('')" style="margin:5px">添加选项</Button>
                    </div>
                    <!-- 添加评分范围编辑 -->
                    <div v-if="question.question_type === 'rating'" class="options-area">
                        <InputNumber v-model="question.min" placeholder="最低分" style="width:100px;margin-right:10px"/>
                        <InputNumber v-model="question.max" placeholder="最高分" style="width:100px"/>
                    </div>
                    <!-- <i-switch v-model="question.is_required" size="large" style="margin-left:10px">
                        <span slot="open">必填</span>
                        <span slot="close">选填</span>
                    </i-switch> -->
                    <i-switch
                    v-model="question.is_required"
                    :value="question.is_required"
                    :true-value="1"
                    :false-value="0"
                    size="large"
                    >
                        <span slot="open">必填</span>
                        <span slot="close">选填</span>
                    </i-switch>
                <Button type="primary" size="small" @click="saveQuestion(index)" style="margin-left:10px">保存</Button>
                    <Button type="error" size="small" @click="cancelEdit(index)" style="margin-left:10px">取消</Button>
                </template>
            </div>
        </draggable>
         <!-- 提交按钮 -->
         <div style="margin: 20px;text-align: center;">
            <Button type="primary" @click="submitQuestions" :disabled="questions.length === 0">提交问卷</Button>
        </div>
        <Modal
            v-model="modalPic"
            width="960px"
            scrollable
            footer-hide
            closable
            title="上传商品图"
            :mask-closable="false"
            :z-index="1"
            >
            <uploadPictures
                :isChoice="isChoice"
                @getPic="getPic"
                v-if="modalPic"
            ></uploadPictures>
        </Modal>
    </div>
</template>

<script>
import draggable from 'vuedraggable'
import { surveyAdd,surveyEdit,surveyDetail } from "@/api/marketing"; 
import { max } from 'moment';
import uploadPictures from "@/components/uploadPictures";
export default{
    components: {
        draggable,
        uploadPictures
    },
    data(){
        return{
            questions: [], // 问题列表
            newQuestion: { // 新问题
                question_type: '',
                is_required: 1,
                question_text: '',
                question_options: [], // 新增选项数组
                min: 1, // 评分最低分
                max: 10  // 评分最高分
            },
            surveyTitle:"",
            top_desc:"",
            bottom_desc:"",
            surveyStatus:1, // 默认启用状态
            itemId:"",
            modalPic: false,
            isChoice: "单选",
            bg_image: "",
        }
    },
    created(){
        if (this.$route.params.id) {
            this.itemId = this.$route.params.id
            this.getSurveyDetail();
        }
    },
    methods: {
         // 获取单张图片信息
         getPic(pc) {
            switch (this.picTit) {
                case "danFrom":
                this.bg_image = pc.att_dir;
                break;
                default:
                this.specsData[this.tableIndex].image = pc.att_dir;
            }
            this.modalPic = false;
        },
        handleRemove() {
            this.bg_image = "";
        },
        // 点击商品图
        modalPicTap(tit, picTit, index) {
            this.modalPic = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit || "";
            this.tableIndex = index;
        },
        getSurveyDetail () {
            surveyDetail(this.$route.params.id).then(res => {
                this.surveyTitle = res.data.title
                this.top_desc = res.data.top_desc
                this.bottom_desc = res.data.bottom_desc
                this.bg_image = res.data.bg_image
                this.surveyStatus = res.data.is_show
                let arrList = res.data.question
                for(let i=0; i<arrList.length; i++){
                    arrList[i].editing = false
                    if(arrList[i].question_type != 'rating'){
                        arrList[i].question_options = Object.values(arrList[i].question_options);
                        
                    }else{
                        arrList[i].max = Number(arrList[i].question_options.max)
                        arrList[i].min = Number(arrList[i].question_options.min)
                        arrList[i].question_options = []
                    }
                }
                this.questions = arrList
            }).catch(err => {
                this.$Message.error(err.msg);
            });
        },
        addQuestion() {
            if (!this.newQuestion.question_type || !this.newQuestion.question_text) {
                this.$Message.error('请选择类型并输入标题');
                return;
            }
            if ((this.newQuestion.question_type === 'radio' || this.newQuestion.question_type === 'checkbox') && 
                (!this.newQuestion.question_options || this.newQuestion.question_options.length < 2)) {
                this.$Message.error('请至少添加两个选项');
                return;
            }
            if (this.newQuestion.question_type === 'rating' && (!this.newQuestion.min || !this.newQuestion.max)) {
                this.$Message.error('请设置评分范围');
                return;
            }
            this.questions.push({
                ...this.newQuestion,
                // id: Date.now(),
                editing: false // 添加默认的编辑状态
            });
            this.newQuestion = { question_type: '', question_text: '', question_options: [], min: 1, max: 10, is_required: 1 };
        },
        addOption() {
            if (!this.newQuestion.question_options) {
                this.$newQuestion.question_options = [];
            }
            this.newQuestion.question_options.push('');
        },
        removeQuestion(index) {
            this.questions.splice(index, 1);
        },
        editQuestion(index) {
            this.questions[index].editing = true;
            this.questions[index].originalData = { ...this.questions[index] };
        },
        saveQuestion(index) {
            const question = this.questions[index];
            if (!question.question_text) {
                this.$Message.error('请输入问题标题');
                return;
            }
            if (question.is_required === undefined) {
                this.$Message.error('请设置是否必填');
                return;
            }
            if ((question.question_type === 'radio' || question.question_type === 'checkbox') && 
                (!question.question_options || question.question_options.length < 2)) {
                this.$Message.error('请至少添加两个选项');
                return;
            }
            if (question.question_type === 'rating' && (!question.min || !question.max)) {
                this.$Message.error('请设置评分范围');
                return;
            }
            question.editing = false;
            delete question.originalData;
        },
        cancelEdit(index) {
            Object.assign(this.questions[index], this.questions[index].originalData);
            this.questions[index].editing = false;
            delete this.questions[index].originalData;
        },
        submitQuestions() {
            if (this.questions.length === 0) {
                this.$Message.warning('请先添加问题');
                return;
            }
            if (!this.surveyTitle) {
                this.$Message.warning('请输入问卷标题');
                return;
            }
            if(this.itemId>0 && this.itemId){
                surveyEdit(this.itemId,{
                    title: this.surveyTitle,
                    top_desc: this.top_desc,
                    bottom_desc: this.bottom_desc,
                    bg_image: this.bg_image,
                    description:"",
                    is_show: this.surveyStatus,
                    questions: this.questions
                })
                .then(async (res) => {
                    this.$Message.success(res.msg);
                    setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/feedback/disposition",
                        });
                    }, 500);
                })
                .catch((res) => {
                    this.$Message.error(res.msg);
                });
            }else{
                surveyAdd({
                    title: this.surveyTitle,
                    bottom_desc: this.bottom_desc,
                    top_desc: this.top_desc,
                    bg_image: this.bg_image,
                    description:"",
                    is_show: this.surveyStatus,
                    questions: this.questions
                })
                .then(async (res) => {
                    this.$Message.success(res.msg);
                    setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/feedback/disposition",
                        });
                    }, 500);
                })
                .catch((res) => {
                    this.$Message.error(res.msg);
                });
            }
        }
    }
}
</script>

<style>
.question-form {
    padding: 20px;
    background: #f8f8f9;
    border-radius: 4px;
    width: 100%;
}

.question-item {
    margin: 15px 0;
    padding: 20px;
    background: #fff;
    border: 1px solid #e8eaec;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}
.question-item:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}
.question-item.editing {
    border-color: #2d8cf0;
    background-color: #f8f8f9;
}

.handle {
    cursor: move;
}
.survey-header {
    margin: 20px 0;
    padding: 20px;
    background: #f8f8f9;
    border-radius: 4px;
    width: 100%;
}
.options-area {
    margin-top: 10px;
    padding: 10px;
    background: #f8f8f9;
    border-radius: 4px;
}
.custom-label {
  display: inline-flex;
  line-height: 1.5;
}
.leftnam{
    display: flex;
    align-items: center;
}
.pictrue{
    width: 58px;
    height: 58px;
    line-height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
    cursor: pointer;
    position: relative;
}
.image{
    width: 100%;
    height: 100%;
}
.btndel {
      position: absolute;
      z-index: 9;
      width: 20px !important;
      height: 20px !important;
      left: 46px;
      top: -4px;
    }
</style>